<template>
  <div class="parent">
    <div class="chart-container">
      <div ref="chartRef" style="height: 500px;"></div>
      <!-- <el-empty v-else description="No data available" /> -->
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted,watch,computed } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import * as echarts from 'echarts';
  import { useLoading } from '../../utils/loading';
  import { useSidebarStore } from '../../store/sidebarStore';
  const { showLoading, hideLoading } = useLoading();
  const BASE_URL = import.meta.env.VITE_API_URL

  const chartRef = ref(null);
  let chartInstance = null;
  const sidebarStore = useSidebarStore();
  const isCollapse = computed(() => sidebarStore.isCollapse);
  
  watch(isCollapse,async(newVal) => {
    await getFault();
  },{ flush: 'post' }) 
  onMounted(() => {
    getFault()
  });
  const getFault = async () => {
    showLoading('loading...')
    try {
      const res = await axios.get(`${BASE_URL}manage/countFaultReason`, {
        params: {
          dealer: null,
        }
      })
      if (res.data && res.data.data) {
        renderChart(res.data.data);
      } else {
        ElMessage.error('Failed to obtain data');
      }
    } catch (error) {
      ElMessage.error(error.msg);
    }finally {
      hideLoading();
    }
  }

  const renderChart = (data) => {
    if (!chartRef.value) return;

    // 准备图表数据
    const titles = data.map(item => item.title);
    const nums = data.map(item => item.num);
    // 计算总数用于百分比计算
    const total = nums.reduce((sum, num) => sum + num, 0);
    // 初始化或重新创建图表实例
    if (chartInstance) {
      chartInstance.dispose();
    }
    chartInstance = echarts.init(chartRef.value);

    // 计算当前显示的柱子数量（根据dataZoom的初始设置）
    const visibleBars = Math.min(titles.length, 6); // 初始显示6条或更少
    
    // 动态设置柱子宽度
    const barWidth = visibleBars <= 6 ? '60px' : '60%';

    // 设置图表配置项
    const option = {
      title: {
        text: 'Statistics of failure causes',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function (params) {
          const param = params[0];
          const percent = ((param.value / total) * 100).toFixed(2);
          return `${param.seriesName}<br/>${param.name}: ${param.value} (${percent}%)`;
        }
      },
      grid: {
        left: '1%',
        right: '1%',
        bottom: '1%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: titles,
        axisLabel: {
          rotate: 30, // 如果标题太长可以旋转
          interval: 0 // 强制显示所有标签
        }
      },
      yAxis: {
        type: 'value',
        name: 'quantity'
      },
      dataZoom: [
        {
          type: 'slider', // 滑动条型 dataZoom
          show: true,
          xAxisIndex: [0], // 控制 x 轴
          start: 0,        // 默认起始位置 0%
          end:  Math.min(50, (6 / titles.length) * 100),
          height: 20,      // 滚动条高度
          bottom: 20,       // 距离底部位置
          fillerColor: '#1890ff', // 滚动条填充色
          borderColor: 'transparent',
          handleStyle: {
            color: '#1890ff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.3)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          emphasis: {
            handleStyle: {
              color: '#0056b3'
            }
          }
        }
      ],
      series: [{
        name: '',
        type: 'bar',
        data: nums,
        barWidth:  barWidth,
        barCategoryGap: '0', // 类目间柱形间距
        itemStyle: {
          color: function (params) {
            const colorList = ['#FF0000', '#FFA500', '#FFFF00', '#008000', '#0000FF', '#4B0082', '#FF00FF'];
            return colorList[params.dataIndex % colorList.length];
          },
          borderRadius: [5, 5, 0, 0]
        },
        label: {
          show: true,
          position: 'top'
        }
      }]
    };

    // 应用配置
    chartInstance.setOption(option);

    // 监听dataZoom事件动态调整柱子宽度
    chartInstance.on('dataZoom', function(params) {
      const option = chartInstance.getOption();
      const currentEnd = params.batch ? params.batch[0].end : params.end;
      const visibleCount = Math.ceil((currentEnd / 100) * titles.length);
      
      const newBarWidth = visibleCount <= 6 ? '60px' : '60%';
      
      chartInstance.setOption({
        series: [{
          barWidth: newBarWidth
        }]
      });
    });

    // 响应式调整
    window.addEventListener('resize', function () {
      chartInstance.resize();
    });
  };
</script>

<style scoped>
  .parent {
    display: flex;
    box-shadow: 0 4px 8px rgba(64, 64, 64, 0.2);
    box-sizing: border-box;
  }
  .chart-container {
    margin-top: 30px;
    width: 100%;
    min-height: 510px;
    padding: 0 20px;
    box-sizing: border-box;
  }
  .card-header {
    font-size: 18px;
    font-weight: bold;
  }
</style>